/*
 * Copyright (c) 2024. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package cirno.open.api.job;

import cirno.open.api.common.ErrorCode;
import cirno.open.api.exception.BusinessException;
import cirno.open.api.utils.RedissonLockUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@RequiredArgsConstructor
public class DailyViewJob {

    private final RedissonLockUtil redissonLockUtil;

    private final StringRedisTemplate redisTemplate;

    /**
     * 每天晚上12点清除当日网站浏览量，并增加到总网站浏览量
     */
    @Scheduled(cron = "0 0 0 * * *")
    public void clearDailyViewCount() {
        final String key = "dailyViewCount";
        final String sumKey = "totalViewCount";
        final String domain = "www.beloved.lt";
        redissonLockUtil.redissonDistributedLocks(key, () -> {
            //今日浏览量
            final String todayViewsStr = redisTemplate.opsForValue().get(key);
            if (todayViewsStr == null) {
                log.error("今日网站{}浏览量统计键值对{}不存在！",domain,key);
                return;
            }
            log.info("今日网站{}浏览量为{}",domain,todayViewsStr);
            //总网站浏览量
            final String totalViewsStr = redisTemplate.opsForValue().get(sumKey);
            if (totalViewsStr == null) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据不存在");
            }
            final long totalViews = Long.parseLong(todayViewsStr) + Long.parseLong(totalViewsStr);
            log.info("网站{}当前总浏览量为{}",domain,totalViews);
            redisTemplate.opsForValue().set(key,"0");
            redisTemplate.opsForValue().set(sumKey, String.valueOf(totalViews));
        });
    }
}
